/**
 * 2018年11月21日下午4:41:05
 * @author 谢进财
 */
package com.baihang.project.ds.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baihang.framework.controller.BaseController;
import com.baihang.framework.kit.PathKit;
import com.baihang.framework.kit.PropKit;
import com.baihang.framework.kit.SSHKit;
import com.baihang.project.ds.service.TuPianService;

/**
 * TuPian 图片
 *
 */
@Controller
@RequestMapping("/tupian")
public class TuPianController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(TuPianController.class);
		@Autowired
		private TuPianService service;
		
		@RequestMapping
		public String index() {			
			return "/project/ds/tupian/index";
		}
		
		@RequestMapping(value="/getPic",produces="application/json;charset=UTF-8")
		@ResponseBody
		public String getPic() {
			String result = service.getPic();
			//System.err.println(result);
			return result;
		}
		
		@RequestMapping(value ="/uploadImage", produces="application/json;charset=UTF-8")
		@ResponseBody
		public String uploadImage(MultipartFile uploadName,String fileName) {
			String oldpath = PathKit.getWebRootPath()+"/upload/"+uploadName.getOriginalFilename();
			logger.info(oldpath);
			String newFileName =fileName+".jpg";
			String filepath = PathKit.getWebRootPath()+"/upload/"+newFileName;
			logger.info(filepath);
			try {
				uploadName.transferTo(new File(filepath));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			SSHKit.SSHSERVERIP=PropKit.get("SSHSERVERIP");
			SSHKit.SSHUSERNAME=PropKit.get("SSHUSERNAME");
			SSHKit.SSHPASSWORD=PropKit.get("SSHPASSWORD");
			File file = new File(filepath);
			byte[] fileByte;
			try {
				fileByte = SSHKit.toByteArray(new FileInputStream(file));
				SSHKit.upload(fileByte, newFileName, PropKit.get("SSHImagePath"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.info(e.getMessage());
				e.printStackTrace();
			} 
			
			return String.format("{\"result\":\"%s\",\"fileName\":\"%s\"}", "true",newFileName);
		}
}
